# -*- coding: utf-8 -*-
# @Time    : 2023/4/19 17:30
# @Author  : wkaanig
# @File    : table_
# @Email   : 15670813638@163.com
# @Software: PyCharm
import re

from utils.tools import replace_str


class TableMixin:
    @staticmethod
    def table2json(response):
        table_dict = TableMixin.table_json(response, save_one_blank=False)
        new_table_dict = {}
        for k, v in table_dict.items():
            new_table_dict.update(TableMixin._try2split_items(k, new_table_dict))
            new_table_dict.update(TableMixin._try2split_items(v, new_table_dict))
            new_table_dict[k] = v
        return new_table_dict

    @staticmethod
    def table_json(table, save_one_blank=True):
        """
        将表格转为json 适应于 key：value 在一行类的表格
        @param table: 使用selector封装后的具有xpath的selector
        @param save_one_blank: 保留一个空白符
        @return:
        """
        data = {}

        trs = table.xpath(".//tr")
        need_reverse_tds = []
        for tr in trs:
            tds = tr.xpath("./td|./th")

            for i in range(0, len(tds), 2):
                if i + 1 > len(tds) - 1:
                    need_reverse_tds.append(tds)
                    break

                key = tds[i].xpath("string(.)").extract_first(default="").strip()
                key = replace_str(key, "[\f\n\r\t\v]", "")
                key = replace_str(key, " +", " " if save_one_blank else "")

                value = tds[i + 1].xpath("string(.)").extract_first(default="").strip()
                value = replace_str(value, "[\f\n\r\t\v]", "")
                value = replace_str(value, " +", " " if save_one_blank else "")

                if key:
                    data[key] = value

        if need_reverse_tds:
            # 反向取一遍
            for tds in need_reverse_tds:
                for i in range(1, len(tds), 2):
                    if i + 1 > len(tds) - 1:
                        need_reverse_tds.append(tds)
                        break

                    key = tds[i].xpath("string(.)").extract_first(default="").strip()
                    key = replace_str(key, "[\f\n\r\t\v]", "")
                    key = replace_str(key, " +", " " if save_one_blank else "")

                    value = tds[i + 1].xpath("string(.)").extract_first(default="").strip()
                    value = replace_str(value, "[\f\n\r\t\v]", "")
                    value = replace_str(value, " +", " " if save_one_blank else "")

                    if key:
                        data[key] = value

        return data

    @staticmethod
    def _try2split_items(text, item):
        tmp_key = TableMixin._replace_key(text)
        if len(tmp_key) > 1:
            new_key, *new_value = re.split(r"[:：]", tmp_key)
            if len(new_key) < 5:
                item[new_key] = ''.join(new_value)
        return item

    @staticmethod
    def _replace_key(text):
        return re.sub(r'\s', '', text)
